package com.micro.ai.agents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.agents.entity.Agent;
import com.micro.ai.agents.entity.AgentVersion;
import com.micro.ai.agents.mapper.AgentMapper;
import com.micro.ai.agents.service.AgentService;
import com.micro.ai.agents.service.AgentVersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 智能体服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class AgentServiceImpl extends ServiceImpl<AgentMapper, Agent> implements AgentService {

    @Autowired(required = false)
    private AgentVersionService agentVersionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Agent create(Agent agent) {
        if (agent == null) {
            throw new BusinessException("A0000", "智能体信息不能为空");
        }
        
        if (!StringUtils.hasText(agent.getTenantId())) {
            throw new BusinessException("A0000", "租户ID不能为空");
        }
        
        if (!StringUtils.hasText(agent.getName())) {
            throw new BusinessException("A0000", "智能体名称不能为空");
        }
        
        // 检查同一租户下名称是否重复
        LambdaQueryWrapper<Agent> query = new LambdaQueryWrapper<>();
        query.eq(Agent::getTenantId, agent.getTenantId())
             .eq(Agent::getName, agent.getName());
        
        Agent existing = this.getOne(query);
        if (existing != null) {
            throw new BusinessException("A0001", "智能体名称已存在: " + agent.getName());
        }
        
        LocalDateTime now = LocalDateTime.now();
        agent.setCreatedAt(now);
        agent.setUpdatedAt(now);
        
        if (agent.getTemperature() == null) {
            agent.setTemperature(new BigDecimal("0.7"));
        }
        if (agent.getMaxTokens() == null) {
            agent.setMaxTokens(2000);
        }
        if (agent.getStatus() == null) {
            agent.setStatus("active");
        }
        if (agent.getVersion() == null) {
            agent.setVersion("1.0.0");
        }
        
        boolean success = this.save(agent);
        if (!success) {
            throw new BusinessException("A0003", "保存智能体失败");
        }
        
        log.info("创建智能体成功: agentId={}, name={}", agent.getId(), agent.getName());
        return agent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Agent update(String id, Agent agent) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("A0000", "智能体ID不能为空");
        }
        if (agent == null) {
            throw new BusinessException("A0000", "智能体信息不能为空");
        }
        
        Agent existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("A0002", "智能体不存在: " + id);
        }
        
        // 如果修改了名称，检查是否重复
        if (StringUtils.hasText(agent.getName()) && !agent.getName().equals(existing.getName())) {
            LambdaQueryWrapper<Agent> query = new LambdaQueryWrapper<>();
            query.eq(Agent::getTenantId, existing.getTenantId())
                 .eq(Agent::getName, agent.getName())
                 .ne(Agent::getId, id);
            
            Agent duplicate = this.getOne(query);
            if (duplicate != null) {
                throw new BusinessException("A0001", "智能体名称已存在: " + agent.getName());
            }
        }
        
        agent.setId(id);
        agent.setUpdatedAt(LocalDateTime.now());
        
        boolean success = this.updateById(agent);
        if (!success) {
            throw new BusinessException("A0003", "更新智能体失败");
        }
        
        log.info("更新智能体成功: agentId={}, name={}", id, agent.getName());
        return agent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("A0000", "智能体ID不能为空");
        }
        
        Agent agent = this.getById(id);
        if (agent == null) {
            throw new BusinessException("A0002", "智能体不存在: " + id);
        }
        
        // 注意：如果有关联的会话，可能需要先处理
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("A0003", "删除智能体失败");
        }
        
        log.info("删除智能体成功: agentId={}, name={}", id, agent.getName());
    }

    @Override
    public Page<Agent> pageQuery(int pageNum, int pageSize, String tenantId, 
                                String keyword, String status) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<Agent> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Agent> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(Agent::getTenantId, tenantId);
        }
        if (StringUtils.hasText(status)) {
            query.eq(Agent::getStatus, status);
        }
        if (StringUtils.hasText(keyword)) {
            query.and(q -> q.like(Agent::getName, keyword)
                          .or().like(Agent::getDescription, keyword));
        }
        
        query.orderByDesc(Agent::getCreatedAt);
        
        return this.page(page, query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(String id, String status) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("A0000", "智能体ID不能为空");
        }
        if (!StringUtils.hasText(status)) {
            throw new BusinessException("A0000", "状态不能为空");
        }
        
        if (!"active".equals(status) && !"inactive".equals(status) && !"training".equals(status)) {
            throw new BusinessException("A0000", "状态值不正确");
        }
        
        Agent agent = this.getById(id);
        if (agent == null) {
            throw new BusinessException("A0002", "智能体不存在: " + id);
        }
        
        agent.setStatus(status);
        agent.setUpdatedAt(LocalDateTime.now());
        
        boolean success = this.updateById(agent);
        if (!success) {
            throw new BusinessException("A0003", "更新智能体状态失败");
        }
        
        log.info("更新智能体状态成功: agentId={}, newStatus={}", id, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Agent publishVersion(String id, String version, String changeLog) {
        Agent agent = this.getById(id);
        if (agent == null) {
            throw new BusinessException("A0002", "智能体不存在: " + id);
        }
        
        // 创建版本记录
        if (agentVersionService != null) {
            AgentVersion agentVersion = new AgentVersion();
            agentVersion.setAgentId(id);
            agentVersion.setVersion(version);
            agentVersion.setChangeLog(changeLog);
            agentVersion.setCreatedBy(agent.getCreatedBy());
            // configSnapshot可以保存当前agent的JSON快照
            agentVersionService.create(agentVersion);
        }
        
        // 更新智能体版本号
        agent.setVersion(version);
        agent.setUpdatedAt(LocalDateTime.now());
        this.updateById(agent);
        
        log.info("发布智能体版本成功: agentId={}, version={}", id, version);
        return agent;
    }
}

